<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./vue.global.js"></script>
  </head>

  <body>
    <div id="app">
      <son></son>
    </div>

    <script>
      const i18nPlugin = {
        // 应用插件时 注入了【语言速查表】 该表为options参数所接收
        // app.use(i18nPlugin, i18nStrings)
        install: (app, options) => {
          // 给全局注入了翻译方法$translate
          // greetings.hi
          // [greetings,hi]
          // scb  greetings => scb.greetings
          // {hi:"哈喽"} hi => 哈喽
          app.config.globalProperties.$translate = (key) => {
            // console.log("key=",key,options);
            return key.split(".").reduce((o, i) => {
              // console.log("o/i",o,i);
              if (o) return o[i];
            }, options);
          };

          // 给全局透传数据
          app.provide("i18n", options);

          /* 注入全局自定义指令 */
          let elem = null;
          let targetColor;
          const highlightHandler = () => {
            elem.style.color = targetColor;
          };
          const highlightRemover = () => {
            elem.style.color = "black";
          };
          app.directive("highlight", {
            mounted(el, binding) {
              elem = el;
              console.log("binding.value", binding.value);
              targetColor = binding.value || "red";
              el.addEventListener("mouseover", highlightHandler);
              el.addEventListener("mouseout", highlightRemover);
            },
            beforeUnmount(el, binding) {
              elem = el;
              el.removeEventListener("mouseover", highlightHandler);
              el.removeEventListener("mouseout", highlightRemover);
            },
          });
        },
      };

      /* 模拟语言速查表 */
      const i18nStrings = {
        greetings: {
          hi: "嗨!",
          WhatAStupid: "真是个小可爱!",
        },
      };

      const app = Vue.createApp({
        mounted() {
          console.log(
            "app mounted: hi => ",
            app.config.globalProperties.$translate("greetings.hi")
          );
        },
      });

      // 应用插件 注入语言速查表
      app.use(i18nPlugin, i18nStrings);

      app.component("son", {
        // 接收i18nPlugin插件全局透传下来的数据
        inject: ["i18n"],

        template: `{{getTranslatedResult}}`,
        data() {
          return {
            word: "WhatAStupid",
          };
        },

        created() {
          console.log("son created: this.i18n=", this.i18n);
        },

        computed: {
          getTranslatedResult() {
            return this.$translate(`greetings.${this.word}`);
          },
        },
      });

      const vm = app.mount("#app");
    </script>
  </body>
</html>
